# -*- coding: utf-8 -*-
from xTkinter import * 
import tkFileDialog
import tkMessageBox as msgBox
import sys
import xmlrpclib
from Validation_Contraintes import *
Validateur =  ValidationContrainte()
class Vue_ReglesAffaires(Frame):
    def __init__(self,master,parent,**cnf):
        self.ListeContraintes = []
        self.ListLabels = []
        self.ListeBoutons = []
        self.ListeTable = []
        self.parent = parent
        self.master=master
        Frame.__init__(self,master,cnf)             
        self.pack(side=LEFT,anchor=NW)
        self.configure(width=800,height=600)
        self.CBTables=xCombobox(self)
        self.CBTables.setLocation(135,0)
        self.CBTables.setWidth(15)
        self.CBTables.setListWidth(25)
        self.CBTables.setListHeight(5)
        self.obtenirTables() 
        self.CBTables.setValidator(self.obtenirContraintes)
        self.CBTables.setText('<Choisir>')
        Requete = "select contrainte_id.nextval from dual"
        Reponse = self.parent.serveur.ExecuterRequeteSQLWhere(Requete)
        if(Reponse[0] == 0):
             msgBox.showerror('PERP 2009 | Édition des tables', 'Une erreur est survenue!\n'+Reponse[1])
        else:
             self.ID_Contraintes = Reponse[1][0][0]
        
      #  self.Regle()
    
    def obtenirTables(self):
        Reponse = self.parent.serveur.ObtenirListeTables(self.parent.user,self.parent.profil)
        if(Reponse[0]==1):
            self.ListeChamps = Reponse[1]
            for i in range(len(self.ListeChamps)):
                self.ListeTable.append(self.ListeChamps[i][0])
                self.CBTables.addItem(self.ListeChamps[i][0])
                self.CBTables.setText(self.ListeChamps[i][0])
        
    def obtenirContraintes(self):
        self.ListeContraintes = []
        Reponse = self.parent.serveur.ObtenirContraintes(self.CBTables.getText())
        for Label in self.ListLabels:
            Label.destroy()
        for Bouton in self.ListeBoutons:
            Bouton.destroy()
        if(Reponse[0]==1):
            self.ListeContraintes = Reponse[1]
            Position = 0
            self.ListeBoutons.append(xButton(self,text="Ajouter Contrainte",width=16, command = self.AjouterContrainte ))
            self.ListeBoutons[len(self.ListeBoutons)-1].setLocation(0,(Position+1)*25+5)
#            self.ListeBoutons.append(xButton(self,text="Ajouter Condition",width=16, command = self.AjouterContrainte ))
#            self.ListeBoutons[len(self.ListeBoutons)-1].setLocation(125,(Position+1)*25+5)

            Position = 1
            for Contrainte in self.ListeContraintes:
                pass
                try:
                    texte = Contrainte['MESSAGE_GUIDE'] 
                    texte = texte + '(' + Contrainte['OPERANDE_GAUCHE'] + '.'
                    texte = texte + Contrainte['ATTRIBUT_GAUCHE']
                    texte = texte + Contrainte['COMPARAISON']
                    texte = texte + Contrainte['OPERANDE_DROITE'] + ')'
                    self.ListLabels.append(xLabel(self,text=texte, width=len(texte)+2, anchor=SW ))
                    self.ListLabels[len(self.ListLabels)-1].setLocation(0,(Position+1)*25+5)
                except:
                    texte = "Contrainte invalide, corrigez-la"
                    self.ListLabels.append(xLabel(self,text=texte, width=len(texte)+2, anchor=SW ))
                    self.ListLabels[len(self.ListLabels)-1].setLocation(0,(Position+1)*25+5)

                self.ListeBoutons.append(xButton(self,text="Editer",width=12, command = lambda contrainte=Contrainte : self.OuvrirFenetreEdition(contrainte)))
                self.ListeBoutons[len(self.ListeBoutons)-1].setLocation(500,(Position+1)*25+5)
                self.ListeBoutons.append(xButton(self,text="Supprimer",width=12, command = lambda contrainte=Contrainte : self.SupprimerContrainte(contrainte)))
                self.ListeBoutons[len(self.ListeBoutons)-1].setLocation(600,(Position+1)*25+5)
                Position = Position + 1
                                 
        else:
          msgBox.showerror('PERP 2009 | Édition des tables', 'Une erreur est survenue!\n'+Reponse[1])
        
    def OuvrirFenetreEdition(self, Contrainte):
        root=Toplevel()
        root.geometry('550x175')
        root.grab_set()
        print Contrainte
        vi=Vue_EditionReglesAffaires(Contrainte, root,self)
        root.mainloop()
    
    
    
    def MettreAJourContrainte(self, Contrainte):
        if Contrainte['ID_CONTRAINTES'] <> '':
            print "Mise a jour" ,Contrainte
            #where = {'valeur_gauche':'ID_CONTRAINTES', 'valeur_droite':Contrainte['ID_CONTRAINTES']}
            where = " where ID_CONTRAINTES = " + Contrainte['ID_CONTRAINTES']
            self.parent.serveur.MettreAJour('PERP_CONTRAINTES', Contrainte, where)
            
        else:
            Contrainte['OPERANDE_GAUCHE'] = self.CBTables.getText()
            Contrainte['ID_CONTRAINTES'] = str(self.ID_Contraintes)
            print "ajouter" ,Contrainte
            self.ID_Contraintes = self.ID_Contraintes + 1
            self.parent.serveur.InsererEnregistrement('PERP_CONTRAINTES', Contrainte)
        self.obtenirContraintes()
    
    def SupprimerContrainte(self, Contrainte):
        print "a effacer " , Contrainte
        where = " where ID_CONTRAINTES = " + Contrainte['ID_CONTRAINTES']
        #where = {'valeur_gauche':'ID_CONTRAINTES', 'valeur_droite':Contrainte['ID_CONTRAINTES']}
        self.parent.serveur.EffacerEnregistrement('PERP_CONTRAINTES', where)
        self.obtenirContraintes()     

    def AjouterContrainte(self):
        root=Toplevel()
        root.geometry('550x175')
        vi=Vue_EditionReglesAffaires(None, root,self)
        root.mainloop()
    
    def PlacerContrainte(self):
        pass
    
    def Regle(self):
        for x in range (1600/25):
            X = x*25
            xLabel(self, text=str(X)).setLocation(X,0)
        for y in range (1200/25):
            Y = y*25
            xLabel(self, text=str(Y)).setLocation(0,Y)      
    
class Vue_EditionReglesAffaires(Frame):
    def __init__(self,Contrainte, master,parent,**cnf):
        KeysList=cnf.keys()
        self.parent = parent
        self.master=master
        self.width=550
        self.height=175
        if ('width' in KeysList):
            self.width=cnf['width']
        if ('height' in KeysList):
            self.height=cnf['height']
        Frame.__init__(self,master,cnf)        
        self.config(bg='Floralwhite')#(bg='#6B979C',relief='raised',bd=3)
        self.pack(side=LEFT, anchor=NW)
        self.configure(width=550,height=175)
        self.Contrainte = Contrainte
       # self.Regle()
    
                       
        Ligne1 = 30
        Ligne2 = 55
        xButton(self,text="Fermer",width=12, command = self.Quitter ).setLocation(400,125)
        
#        self.BoutonDynamiqueStatique = xButton(self,text="Statique",width=12, command = self.DynamiqueStatique )
#        self.BoutonDynamiqueStatique.setLocation(400,5)
        
        self.Attribut1_Label=xLabel(self,text='Attribut',height=1,width=20)
        self.Attribut1_Label.setLocation(x=5,y=Ligne1)
        self.Attribut_Operande_Gauche=xCombobox(self,width=20)
        self.Attribut_Operande_Gauche.setLocation(x=5,y=Ligne2)
        
        self.Attribut_Operande_Gauche.setListWidth(25)
        self.Attribut_Operande_Gauche.setListHeight(5)
        
        self.Comparaison_Label=xLabel(self,text='Comparaison',height=1,width=10)
        self.Comparaison_Label.setLocation(x=150,y=Ligne1)
        self.Comparaison_Combo_Box=xCombobox(self)
        self.Comparaison_Combo_Box.width=10
        self.Comparaison_Combo_Box.setListWidth(25)
        self.Comparaison_Combo_Box.setListHeight(5)
        self.Comparaison_Combo_Box.setLocation(x=150,y=Ligne2)
        
        self.Table_Operande_Droite=xCombobox(self,width=20)
        self.Table_Operande_Droite.setLocation(x=400,y=Ligne2)
        self.Table2_Label=xLabel(self,text='Table/Statique',height=1,width=20)
        self.Table2_Label.setLocation(x=250,y=Ligne1)
        
        self.Attribut2_Label=xLabel(self,text='Valeur',height=1,width=20)
        self.Attribut2_Label.setLocation(x=400,y=Ligne1)
        self.Attribut_Operande_Droite=xCombobox(self,width=20)
        self.Attribut_Operande_Droite.setLocation(x=250,y=Ligne2)
        
        self.Attribut_Operande_Droite.setListWidth(25)
        self.Attribut_Operande_Droite.setListHeight(5)
        
        self.Message_Erreur_Text=xEntry(self,text='Message d''erreur',width=60)
        self.Message_Erreur_Text.setLocation(x=5,y=100)
        self.Message_Erreur_Label=xLabel(self,text='Message d''erreur',height=1,width=15)
        self.Message_Erreur_Label.setLocation(x=5,y=75)
                
        self.Conseils_Label=xLabel(self,text='Conseils',height=1,width=10)
        self.Conseils_Label.setLocation(x=5,y=125)
        self.Conseils_Text=xEntry(self,text='Conseils',width=60)
        self.Conseils_Text.setLocation(x=5,y=150)
        
        self.AssociationColonneChamps = {
                                        "ATTRIBUT_GAUCHE":self.Attribut_Operande_Gauche,
                                        "COMPARAISON":self.Comparaison_Combo_Box,
                                        "OPERANDE_DROITE":self.Table_Operande_Droite,
                                        "ATTRIBUT_DROITE":self.Attribut_Operande_Droite,
                                        "MESSAGE_ERREUR":self.Message_Erreur_Text,
                                        "MESSAGE_GUIDE":self.Conseils_Text,
                                        }
        self.initialiserComboBox()
        self.Attribut_Operande_Droite.setValidator(self.ObtenirChamps)
        self.RemplirChamp(self.Contrainte)
        
        pass

#    def DynamiqueStatique(self):
#        if self.BoutonDynamiqueStatique.getText() == "Dynamique":
#            self.BoutonDynamiqueStatique.setText("Statique")
#            self.Attribut_Operande_Droite.setVisible(False) 
#            self.Attribut2_Label.setVisible(False) 
#        else:
#            self.BoutonDynamiqueStatique.setText("Dynamique")
#            self.Attribut_Operande_Droite.setVisible(True) 
#            self.Attribut2_Label.setVisible(True)

    def Quitter(self):
        #if MsgBox.askokcancel("Attention", "Vous annulez l'ouverture de session."):
        self.destroy()
        self.master.destroy()
        if self.Contrainte == None:
            self.Contrainte={}
            self.Contrainte['ID_CONTRAINTES'] = ''
        for champs in self.AssociationColonneChamps.keys():
            if self.AssociationColonneChamps[champs] <> None:
                self.Contrainte[champs] = self.AssociationColonneChamps[champs].getText()
        self.parent.MettreAJourContrainte(self.Contrainte)
        pass
    
    def close(self):
        self.destroy()
        pass
    
    def ObtenirChamps(self):
        self.Table_Operande_Droite.clear()
        if self.Attribut_Operande_Droite.getText() <> "<<STATIQUE>>":
            print self.Attribut_Operande_Droite.getText()
            for Champ in self.parent.parent.serveur.ObtenirListeChamps(self.Attribut_Operande_Droite.getText())[1]:
                    print Champ
                    self.Table_Operande_Droite.addItem(Champ[0])
        else:
            self.Table_Operande_Droite.setText('')
                    
    def initialiserComboBox(self):
        #operande
        for Operande in Validateur.getOperande():
            self.Comparaison_Combo_Box.addItem(Operande)
        print  self.parent.ListeTable
        self.Attribut_Operande_Droite.addItem("<<STATIQUE>>")
        for table in self.parent.ListeTable:
                self.Attribut_Operande_Droite.addItem(table)
        for Champ in self.parent.parent.serveur.ObtenirListeChamps(self.parent.CBTables.getText())[1]:
            print Champ
            self.Attribut_Operande_Gauche.addItem(Champ[0])
        if self.Attribut_Operande_Droite.getText() <> "<<STATIQUE>>":
            print self.Attribut_Operande_Droite.getText()
            for Champ in self.parent.parent.serveur.ObtenirListeChamps(self.Attribut_Operande_Droite.getText())[1]:
                    print Champ
                    self.Attribut_Operande_Gauche.addItem(Champ[0])
    
    def RemplirChamp(self, Contrainte):
        print Contrainte
        if self.Contrainte == None:
            for Champs in self.AssociationColonneChamps.keys():
                try:
                    if self.AssociationColonneChamps[Champs] <> None:
                        self.AssociationColonneChamps[Champs].setText('')
                    
                except:
                    pass
        else:
            for Champs in self.Contrainte:
                try:
                    if self.AssociationColonneChamps.has_key(Champs):
                        if self.AssociationColonneChamps[Champs] <> None:
                            self.AssociationColonneChamps[Champs].setText(Contrainte[Champs])
                except:
                    pass
        pass   

    def Regle(self):
        for x in range (1600/25):
            X = x*25
            xLabel(self, text=str(X)).setLocation(X,0)
        for y in range (1200/25):
            Y = y*25
            xLabel(self, text=str(Y)).setLocation(0,Y)       


#class Controleur:
#    def __init__(self):
#        self.user = "ADMIN"
#        self.profil = "ADMIN"
#        Serveur='http://localhost:8000'
#        self.serveur=xmlrpclib.ServerProxy(Serveur)
#        root=Tk()
#        root.geometry('800x400')
#        vi=Vue_ReglesAffaires(root,self)
#        root.mainloop()       
#
#Controleur = Controleur()

    
    
    
